<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :lock-scroll="true"
    :title="title"
    top="5vh"
    :visible.sync="dialogFormVisible"
    width="666px"
    @close="close"
  >
    <div class="resident-modal">
      <el-collapse v-model="collapseList">
        <el-collapse-item name="1" title="居民基本信息">
          <el-form
            ref="form"
            :label-position="'right'"
            label-width="auto"
            :model="form"
            :rules="rules"
          >
            <el-form-item label="证件类型" prop="certType">
              <el-select
                v-model="form.certType"
                class="full-select"
                clearable
                placeholder="请选择证件类型"
              >
                <el-option
                  v-for="item in certType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="certNo">
              <el-input v-model.trim="form.certNo" clearable max="30" />
            </el-form-item>
            <el-form-item label="居民照片" prop="photo">
              <el-upload
                :action="upToServerUrl"
                :before-upload="beforeAvatarUpload"
                class="avatar-uploader"
                :on-success="handleAvatarSuccess"
                :show-file-list="false"
                :with-credentials="true"
              >
                <img
                  v-if="form.photo"
                  alt="图片预览"
                  class="avatar"
                  :src="prevUrl + form.photo"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <!--              <el-input v-model="form.photo" style="display: none" />-->
            </el-form-item>
            <el-form-item label="居民姓名" prop="name">
              <el-input
                v-model.trim="form.name"
                clearable
                max="30"
                placeholder="请输入居民姓名"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model.trim="form.phone"
                clearable
                placeholder="请输入手机号码"
              />
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                class="full-select"
                clearable
                placeholder="请选择出生日期"
                type="date"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select
                v-model="form.sex"
                class="full-select"
                clearable
                placeholder="请选择性别"
              >
                <el-option
                  v-for="item in sexType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="国籍" prop="nationCode">
              <el-select
                v-model="form.nationCode"
                class="full-select"
                clearable
                placeholder="请选择国籍"
              >
                <el-option
                  v-for="item in countryList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="民族" prop="nation">
              <el-select
                v-model="form.nation"
                class="full-select"
                clearable
                placeholder="请选择民族"
              >
                <el-option
                  v-for="item in nationList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="政治面貌" prop="politicalClimate">
              <el-select
                v-model="form.politicalClimate"
                class="full-select"
                clearable
                placeholder="请输入政治面貌"
              >
                <el-option
                  v-for="item in policyRole"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="居住地址" prop="liveAddress">
              <el-alert :closable="false" show-icon type="info">
                <slot name="description">
                  地址格式：
                  <strong>
                    市/区县/乡镇街道/街路巷自然村/门牌号/小区名称/楼牌号/单元/层数/户室/地址ID/经度/纬度
                  </strong>
                  <br />
                  填写示例(没有的内容用'空'代替)：北京市/昌平区/史各庄街道/农学院北路/9号/领袖惠谷A区/1号楼/1单元/1层/102室/空/116.1113214/40.12321234
                </slot>
              </el-alert>
              <el-input
                v-model.trim="form.liveAddress"
                clearable
                placeholder="请输入居住地址"
                :rows="4"
                type="textarea"
              />
            </el-form-item>
            <el-form-item label="户籍省市区" prop="provinceCityList">
              <el-cascader
                v-model="form.provinceCityList"
                class="full-select"
                clearable
                :options="treeList"
              />
            </el-form-item>
            <el-form-item label="户籍详细地址" prop="address">
              <el-input
                v-model.trim="form.address"
                clearable
                placeholder="请输入详细地址"
              />
            </el-form-item>
            <!--新增字段-->
            <el-form-item label="是否购置车辆" prop="isBuyCar">
              <el-select
                v-model="form.isBuyCar"
                class="full-select"
                clearable
                placeholder="请选择是否购置车辆"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="家庭宠物" prop="isPet">
              <el-select
                v-model="form.isPet"
                class="full-select"
                clearable
                placeholder="请选择家庭宠物"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否购置电动车" prop="isElecCar">
              <el-select
                v-model="form.isElecCar"
                class="full-select"
                clearable
                placeholder="请选择是否购置电动车"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="婚姻状况" prop="maritalStatus">
              <el-select
                v-model="form.maritalStatus"
                class="full-select"
                clearable
                placeholder="请选择婚姻状况"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="从业状况" prop="workStatus">
              <el-select
                v-model="form.workStatus"
                class="full-select"
                clearable
                placeholder="请选择从业状况"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否军人" prop="isSoldier">
              <el-select
                v-model="form.isSoldier"
                class="full-select"
                clearable
                placeholder="请选择是否军人"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="有无暂住证" prop="hasLivePermit">
              <el-select
                v-model="form.hasLivePermit"
                class="full-select"
                clearable
                placeholder="请选择有无暂住证"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="离开户口地日期" prop="outDate">
              <el-date-picker
                v-model="form.outDate"
                class="full-select"
                clearable
                placeholder="请选择离开户口地日期"
                type="date"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="离开户口地原因" prop="outReason">
              <el-input
                v-model.trim="form.outReason"
                clearable
                max="50"
                placeholder="请输入离开户口地原因"
              />
            </el-form-item>
            <el-form-item label="文化程度" prop="education">
              <el-select
                v-model="form.education"
                class="full-select"
                clearable
                placeholder="请选择文化程度"
              >
                <el-option
                  v-for="item in [
                    { label: '无', value: '0' },
                    { label: '小学', value: '1' },
                    { label: '初中', value: '2' },
                    { label: '高中', value: '3' },
                    { label: '大专', value: '4' },
                    { label: '本科', value: '5' },
                    { label: '研究生', value: '6' },
                    { label: '硕士', value: '7' },
                    { label: '博士', value: '8' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="入党日期" prop="joinPartyDate">
              <el-date-picker
                v-model="form.joinPartyDate"
                class="full-select"
                clearable
                placeholder="请选择入党日期"
                type="date"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="党组织关系" prop="partyRelation">
              <el-input
                v-model.trim="form.partyRelation"
                clearable
                max="20"
                placeholder="请输入党组织关系"
              />
            </el-form-item>
            <el-form-item label="工作单位" prop="workCompanny">
              <el-input
                v-model.trim="form.workCompany"
                clearable
                max="20"
                placeholder="请输入工作单位"
              />
            </el-form-item>
            <el-form-item label="是否网格员" prop="isGrid">
              <el-select
                v-model="form.isGrid"
                class="full-select"
                clearable
                placeholder="请选择是否网格员"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否志愿者" prop="isVolunteer">
              <el-select
                v-model="form.isVolunteer"
                class="full-select"
                clearable
                placeholder="请选择是否志愿者"
              >
                <el-option
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <el-collapse-item name="2" title="房屋信息">
          <el-form
            ref="houseForm"
            :label-position="'right'"
            label-width="auto"
            :model="houseForm"
            :rules="houseRules"
          >
            <el-form-item label="街道" prop="townNo">
              <el-select
                v-model="houseForm.townNo"
                class="full-select"
                clearable
                placeholder="请选择街道"
                @change="changeTown"
              >
                <el-option
                  v-for="item in townList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="小区" prop="areaNo">
              <el-select
                v-model="houseForm.areaNo"
                class="full-select"
                clearable
                placeholder="请选择小区"
                @change="changeArea"
              >
                <el-option
                  v-for="item in areaList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="楼牌号" prop="builderId">
              <el-select
                v-model="houseForm.builderId"
                class="full-select"
                clearable
                placeholder="请选择楼牌号"
                @change="changeBuilder"
              >
                <el-option
                  v-for="item in builderList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="房间号" prop="roomList">
              <el-cascader
                v-model="houseForm.roomList"
                class="full-select"
                clearable
                :options="roomList"
              />
            </el-form-item>
            <el-form-item label="户型" prop="roomNum">
              <el-select
                v-model="houseForm.roomNum"
                class="full-select"
                clearable
                placeholder="请选择户型"
              >
                <el-option
                  v-for="item in roomType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="房屋联系人姓名" prop="linkName">
              <el-input
                v-model.trim="houseForm.linkName"
                clearable
                placeholder="请输入房屋联系人姓名"
              />
            </el-form-item>
            <el-form-item label="房屋联系人手机号" prop="linkPhone">
              <el-input
                v-model.trim="houseForm.linkPhone"
                clearable
                placeholder="请输入房屋联系人手机号"
              />
            </el-form-item>
            <el-form-item label="房屋联系人证件类型" prop="linkCertType">
              <el-select
                v-model="houseForm.linkCertType"
                class="full-select"
                clearable
                placeholder="请选择房屋联系人证件类型"
              >
                <el-option
                  v-for="item in certType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="房屋联系人证件号码" prop="linkCertNo">
              <el-input
                v-model.trim="houseForm.linkCertNo"
                clearable
                placeholder="请输入房屋联系人证件号码"
              />
            </el-form-item>
            <!--新增房屋字段-->
            <el-form-item label="房屋面积" prop="houseArea">
              <el-input
                v-model.trim="houseForm.houseArea"
                clearable
                max="10"
                placeholder="请输入房屋面积"
              />
            </el-form-item>
            <el-form-item label="房屋性质" prop="houseNature">
              <el-select
                v-model="form.houseNature"
                class="full-select"
                clearable
                placeholder="请选择房屋性质"
              >
                <el-option
                  v-for="item in [
                    { label: '无', value: '0' },
                    { label: '商品房', value: '1' },
                    { label: '公房', value: '2' },
                    { label: '经济适用房', value: '3' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="房屋用途" prop="houseUsage">
              <el-select
                v-model="form.houseUsage"
                class="full-select"
                clearable
                placeholder="请选择房屋用途"
              >
                <el-option
                  v-for="item in [
                    { label: '小区', value: '1' },
                    { label: '公寓', value: '2' },
                  ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <el-collapse-item name="3" title="车辆信息">
          <el-form
            ref="carForm"
            :label-position="'right'"
            label-width="auto"
            :model="carForm"
            :rules="carRules"
          >
            <el-form-item label="车牌号码" prop="plateNo">
              <el-input
                v-model.trim="carForm.plateNo"
                clearable
                placeholder="请输入车牌号码"
                @change="checkCarRules"
              />
            </el-form-item>
            <el-form-item label="车牌颜色" prop="plateColor">
              <el-select
                v-model="carForm.plateColor"
                class="full-select"
                clearable
                placeholder="请选择车牌颜色"
                @change="checkCarRules"
              >
                <el-option
                  v-for="item in plateColor"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="车辆品牌" prop="brand">
              <el-select
                v-model="carForm.brand"
                class="full-select"
                clearable
                placeholder="请选择车辆品牌"
                @change="checkCarRules"
              >
                <el-option
                  v-for="item in carBrand"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="车辆类型" prop="carType">
              <el-select
                v-model="carForm.carType"
                class="full-select"
                clearable
                placeholder="请选择车辆类型"
                @change="checkCarRules"
              >
                <el-option
                  v-for="item in carType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="车辆颜色" prop="carColor">
              <el-select
                v-model="carForm.carColor"
                class="full-select"
                clearable
                placeholder="请选择车辆颜色"
                @change="checkCarRules"
              >
                <el-option
                  v-for="item in carColor"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="车辆使用人姓名" prop="useName">
              <el-input
                v-model.trim="carForm.useName"
                clearable
                placeholder="请输入车辆使用人姓名"
                @change="checkCarRules"
              />
            </el-form-item>
            <el-form-item label="车辆使用人证件类型" prop="useCertType">
              <el-select
                v-model="carForm.useCertType"
                class="full-select"
                clearable
                placeholder="请输入车辆使用人证件类型"
                @change="checkCarRules"
              >
                <el-option
                  v-for="item in certType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="车辆使用人证件号码" prop="useCertNo">
              <el-input
                v-model.trim="carForm.useCertNo"
                clearable
                placeholder="请输入车辆使用人证件号码"
                @change="checkCarRules"
              />
            </el-form-item>
            <!--            <el-form-item label="车辆使用人居住地址" prop="useAddress">-->
            <!--              <el-input-->
            <!--                v-model="carForm.useAddress"-->
            <!--                clearable-->
            <!--                placeholder="请输入车辆使用人居住地址"-->
            <!--                @change="checkCarRules"-->
            <!--              />-->
            <!--            </el-form-item>-->
            <el-form-item label="车辆使用人居住地址" prop="useAddress">
              <el-alert :closable="false" show-icon type="info">
                <slot name="description">
                  地址格式：
                  <strong>
                    市/区县/乡镇街道/街路巷自然村/门牌号/小区名称/楼牌号/单元/层数/户室/地址ID/经度/纬度
                  </strong>
                  <br />
                  填写示例(没有的内容用'空'代替)：北京市/昌平区/史各庄街道/农学院北路/9号/领袖惠谷A区/1号楼/1单元/1层/102室/空/116.1113214/40.12321234
                </slot>
              </el-alert>
              <el-input
                v-model.trim="carForm.useAddress"
                clearable
                placeholder="请输入车辆使用人居住地址"
                :rows="4"
                type="textarea"
                @change="checkCarRules"
              />
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button :loading="isSaving" type="primary" @click="save">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import {
    getTownList,
    getAreaList,
    getBuilderList,
    getRoomList,
    addResident,
    getResidentById,
    updateResident,
    uploadUrl,
  } from '@/api/resident'
  import store from '@/store'
  import { mapGetters } from 'vuex'
  import { picBaseUrl, baseURL } from '@/config'

  // 转换树状列表
  function transTree(list) {
    const reCall = (item) => {
      item.value = item.id + ':' + item.name
      item.label = item.name
      if (Array.isArray(item.children) && item.children.length > 0) {
        item.children.forEach((v) => {
          reCall(v)
        })
      }
    }
    list.forEach((v) => {
      reCall(v)
    })
  }

  export default {
    name: 'ResidentEdit',
    data() {
      const photoCheck = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请上传照片'))
        } else {
          callback()
        }
      }
      return {
        collapseList: ['1', '2', '3'],
        imageUrl: '',
        upToServerUrl: baseURL + uploadUrl,
        prevUrl: '',
        isSaving: false,
        form: {
          address: null,
          areaNo: null,
          birthday: null,
          certNo: null,
          certType: null,
          city: null,
          cityCode: null,
          county: null,
          countyCode: null,
          liveAddress: null,
          name: null,
          nation: null,
          nationCode: null,
          phone: null,
          photo: null,
          politicalClimate: null,
          province: null,
          provinceCode: null,
          roomId: null,
          sex: null,
          townNo: null,
          provinceCityList: [],
          education: null,
          hasLivePermit: null,
          isBuyCar: null,
          isElecCar: null,
          isGrid: null,
          isPet: null,
          isSoldier: null,
          isVolunteer: null,
          joinPartyDate: null,
          maritalStatus: null,
          outDate: null,
          outReason: null,
          partyRelation: null,
          workStatus: null,
          workCompany: null,
        },
        houseForm: {
          areaNo: null,
          builderId: null,
          builderName: null,
          floorId: null,
          floorName: null,
          houseId: null,
          linkCertNo: null,
          linkCertType: null,
          linkName: null,
          linkPhone: null,
          roomId: null,
          roomName: null,
          roomNum: null,
          townNo: null,
          unitId: null,
          unitName: null,
          roomList: [],
          houseArea: null,
          houseNature: null,
          houseUsage: null,
        },
        carForm: {
          areaNo: null,
          brand: null,
          carColor: null,
          carType: null,
          parkType: null,
          plateColor: null,
          plateNo: null,
          townNo: null,
          useAddress: null,
          useCertNo: null,
          useCertType: null,
          useName: null,
        },
        rules: {
          certType: [
            { required: true, trigger: 'change', message: '请输入证件类型' },
          ],
          certNo: [
            { required: true, trigger: 'blur', message: '请输入证件号码' },
          ],
          photo: [{ required: true, validator: photoCheck, trigger: 'blur' }],
          name: [{ required: true, trigger: 'blur', message: '请输入姓名' }],
          phone: [
            { required: true, trigger: 'blur', message: '请输入手机号码' },
          ],
          birthday: [
            { required: true, trigger: 'blur', message: '请选择生日' },
          ],
          sex: [{ required: true, trigger: 'change', message: '请选择性别' }],
          nationCode: [
            { required: true, trigger: 'change', message: '请选择国籍' },
          ],
          nation: [
            { required: true, trigger: 'change', message: '请选择民族' },
          ],
          politicalClimate: [
            { required: true, trigger: 'change', message: '请选择政治面貌' },
          ],
          liveAddress: [
            { required: true, trigger: 'blur', message: '请输入居住地址' },
          ],
          provinceCityList: [
            { required: true, trigger: 'change', message: '请选择省市区' },
          ],
          address: [
            { required: true, trigger: 'blur', message: '请选择详细地址' },
          ],
        },
        houseRules: {
          townNo: [
            { required: true, trigger: 'change', message: '请选择街道' },
          ],
          areaNo: [
            { required: true, trigger: 'change', message: '请选择小区' },
          ],
          builderId: [
            { required: true, trigger: 'change', message: '请选择楼牌号' },
          ],
          roomList: [
            { required: true, trigger: 'change', message: '请选择房间号' },
          ],
          roomNum: [
            { required: true, trigger: 'change', message: '请选择户型' },
          ],
          linkName: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择房屋联系人姓名',
            },
          ],
          linkPhone: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择房屋联系人手机号',
            },
          ],
          linkCertType: [
            {
              required: true,
              trigger: 'change',
              message: '请选择房屋联系人证件类型',
            },
          ],
          linkCertNo: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择房屋联系人证件号码',
            },
          ],
        },
        carRules: {},
        title: '',
        dialogFormVisible: false,
        townList: [],
        areaList: [],
        builderList: [],
        roomList: [],
        currentTownId: null,
      }
    },
    computed: {
      ...mapGetters({
        treeList: 'user/treeList',
        certType: 'dict/certType',
        carColor: 'dict/carColor',
        carBrand: 'dict/carBrand',
        carType: 'dict/carType',
        countryList: 'dict/countryList',
        sexType: 'dict/sexType',
        nationList: 'dict/nationList',
        policyRole: 'dict/policyRole',
        roomType: 'dict/roomType',
        plateColor: 'dict/plateColor',
      }),
    },
    mounted() {
      // 获取省市区列表
      this.getProvinceTree()
      // 获取街道列表
      this._getTownList()
    },
    methods: {
      clearCarRule() {
        this.carRules = {}
        if (this.$refs['carForm']) {
          this.$refs['carForm'].clearValidate()
        }
      },
      checkCarRules() {
        let isEmpty = true
        for (let key in this.carForm) {
          if (this.carForm[key]) {
            isEmpty = false
            break
          }
        }
        console.log(this.carForm)
        console.log(isEmpty)
        if (isEmpty) {
          this.clearCarRule()
        } else {
          this.carRules = {
            plateNo: [
              { required: true, trigger: 'blur', message: '请输入车牌号' },
            ],
            plateColor: [
              { required: true, trigger: 'change', message: '请选择车牌颜色' },
            ],
            brand: [
              { required: true, trigger: 'change', message: '请选择车辆品牌' },
            ],
            carType: [
              { required: true, trigger: 'change', message: '请选择车辆类型' },
            ],
            carColor: [
              { required: true, trigger: 'change', message: '请选择车辆颜色' },
            ],
            useName: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入车辆使用人姓名',
              },
            ],
            useCertNo: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入车辆使用人证件号码',
              },
            ],
            useAddress: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入车辆使用人居住地址',
              },
            ],
            useCertType: [
              {
                required: true,
                trigger: 'change',
                message: '请选择车辆使用人证件类型',
              },
            ],
          }
        }
      },
      _getTownList() {
        getTownList()
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              this.townList = res.data
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      _getAreaList(townId) {
        if (townId === undefined || townId === null || townId === '') {
          return
        }
        getAreaList(townId)
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              this.areaList = res.data
              if (this.currentTownId) {
                for (let i = 0; i < res.data.length; i++) {
                  if (res.data[i].code === this.houseForm.areaNo) {
                    this._getBuilderList(res.data[i].id)
                    break
                  }
                }
              }
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      _getBuilderList(areaId) {
        getBuilderList(areaId)
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              this.builderList = res.data
              if (this.currentTownId) {
                for (let i = 0; i < res.data.length; i++) {
                  if (res.data[i].id === this.houseForm.builderId) {
                    this._getRoomList(res.data[i].id)
                    break
                  }
                }
              }
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      _getRoomList(builderId) {
        getRoomList(builderId)
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              transTree(res.data)
              this.roomList = res.data
              // if (this.currentTownId) {
              //   this.$set(this.houseForm, 'roomList', [
              //     ...this.houseForm.roomList,
              //   ])
              // }
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      getProvinceTree() {
        store.dispatch('user/setTreeList')
      },
      changeTown(code) {
        let id = ''
        for (let i = 0; i < this.townList.length; i++) {
          if (this.townList[i].code === code) {
            id = this.townList[i].id
            break
          }
        }
        // console.log('changTown', id)
        this.form.area = ''
        this.form.builder = ''
        this.form.room = ''
        this.areaList = []
        this.builderList = []
        this.roomList = []
        this._getAreaList(id)
      },
      changeArea(code) {
        let id = ''
        for (let i = 0; i < this.areaList.length; i++) {
          if (this.areaList[i].code === code) {
            id = this.areaList[i].id
            break
          }
        }
        // console.log('changeArea', id)
        this.form.builder = ''
        this.form.room = ''
        this.builderList = []
        this.roomList = []
        this._getBuilderList(id)
      },
      changeBuilder(id) {
        // console.log('changeBuilder', id)
        this.form.room = ''
        this.roomList = []
        this._getRoomList(id)
      },
      showEdit(rowBase) {
        // console.log(rowBase)
        if (!rowBase) {
          this.title = '新增居民信息'
        } else {
          this.title = '编辑居民信息'
          getResidentById(rowBase.id)
            .then((res) => {
              if (res && res.data) {
                this.handleEditForm(res.data)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.$refs['houseForm'].resetFields()
        this.$refs['carForm'].resetFields()
        this.form = this.$options.data().form
        this.houseForm = this.$options.data().houseForm
        this.carForm = this.$options.data().carForm
        this.dialogFormVisible = false
        this.currentTownId = null
        this.clearCarRule()
      },
      handleEditForm(row) {
        const { resident, house, car } = row
        this.form = {
          address: resident.address || null,
          areaNo: resident.areaNo || null,
          birthday: resident.birthday || null,
          certNo: resident.certNo || null,
          certType: resident.certType || null,
          city: resident.city || null,
          cityCode: resident.cityCode || null,
          county: resident.county || null,
          countyCode: resident.countyCode || null,
          liveAddress: resident.liveAddress || null,
          name: resident.name || null,
          nation: resident.nation || null,
          nationCode: resident.nationCode || null,
          phone: resident.phone || null,
          photo: resident.photo ? picBaseUrl + resident.photo : null,
          politicalClimate: resident.politicalClimate || null,
          province: resident.province || null,
          provinceCode: resident.provinceCode || null,
          roomId: resident.roomId || null,
          sex: resident.sex || null,
          townNo: resident.townNo || null,
          education: resident.education || null,
          hasLivePermit: resident.hasLivePermit || null,
          isBuyCar: resident.isBuyCar || null,
          isElecCar: resident.isElecCar || null,
          isGrid: resident.isGrid || null,
          isPet: resident.isPet || null,
          isSoldier: resident.isSoldier || null,
          isVolunteer: resident.isVolunteer || null,
          joinPartyDate: resident.joinPartyDate || null,
          maritalStatus: resident.maritalStatus || null,
          outDate: resident.outDate || null,
          outReason: resident.outReason || null,
          partyRelation: resident.partyRelation || null,
          workStatus: resident.workStatus || null,
          workCompany: resident.workCompany || null,
          provinceCityList:
            resident.provinceCode && resident.cityCode && resident.countyCode
              ? [
                  resident.province + ':' + resident.provinceCode,
                  resident.city + ':' + resident.cityCode,
                  resident.county + ':' + resident.countyCode,
                ]
              : [],
          id: resident.residentId,
        }
        this.houseForm = {
          areaNo: house.areaNo || null,
          builderName: house.builderName || null,
          floorId: house.floorId || null,
          floorName: house.floorName || null,
          builderId: house.builderId || null,
          linkCertNo: house.linkCertNo || null,
          linkCertType: house.linkCertType || null,
          linkName: house.linkName || null,
          linkPhone: house.linkPhone || null,
          roomId: house.roomId || null,
          roomName: house.roomName || null,
          roomNum: house.roomNum || null,
          townNo: house.townNo || null,
          unitId: house.unitId || null,
          unitName: house.unitName || null,
          houseId: house.houseId,
          houseArea: house.houseArea || null,
          houseNature: house.houseNature || null,
          houseUsage: house.houseUsage || null,
          roomList:
            house.roomName && house.unitName && house.floorName
              ? [
                  house.unitId + ':' + house.unitName,
                  house.floorId + ':' + house.floorName,
                  house.roomId + ':' + house.roomName,
                ]
              : [],
        }
        this.carForm = {
          areaNo: car.areaNo || null,
          brand: car.brand || null,
          carColor: car.carColor || null,
          carType: car.carType || null,
          parkType: null,
          plateColor: car.plateColor || null,
          plateNo: car.plateNo || null,
          townNo: car.townNo || null,
          useAddress: car.useAddress || null,
          useCertNo: car.useCertNo || null,
          useCertType: car.useCertType || null,
          useName: car.useName || null,
          carId: car.carId,
        }
        this.currentTownId = null
        if (this.form.townNo) {
          this.townList.forEach((v) => {
            if (v.code === this.form.townNo) {
              this.currentTownId = v.id
            }
          })
          if (this.currentTownId) {
            this._getAreaList(this.currentTownId)
          }
        }
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          let houseValid = false
          this.$refs['houseForm'].validate((hValid) => {
            houseValid = hValid
          })
          if (valid && houseValid) {
            let province = null
            let provinceCode = null
            let city = null
            let cityCode = null
            let county = null
            let countyCode = null
            if (this.form.provinceCityList[0]) {
              const valueArr = this.form.provinceCityList[0].split(':')
              if (valueArr[0] && valueArr[1]) {
                province = valueArr[0]
                provinceCode = valueArr[1]
              }
            }
            if (this.form.provinceCityList[1]) {
              const valueArr = this.form.provinceCityList[1].split(':')
              if (valueArr[0] && valueArr[1]) {
                city = valueArr[0]
                cityCode = valueArr[1]
              }
            }
            if (this.form.provinceCityList[2]) {
              const valueArr = this.form.provinceCityList[2].split(':')
              if (valueArr[0] && valueArr[1]) {
                county = valueArr[0]
                countyCode = valueArr[1]
              }
            }
            let unitName = null
            let unitId = null
            let floorName = null
            let floorId = null
            let roomId = null
            let roomName = null
            if (this.houseForm.roomList[0]) {
              const valueArr = this.houseForm.roomList[0].split(':')
              if (valueArr[0] && valueArr[1]) {
                unitId = valueArr[0]
                unitName = valueArr[1]
              }
            }
            if (this.houseForm.roomList[1]) {
              const valueArr = this.houseForm.roomList[1].split(':')
              if (valueArr[0] && valueArr[1]) {
                floorId = valueArr[0]
                floorName = valueArr[1]
              }
            }
            if (this.houseForm.roomList[2]) {
              const valueArr = this.houseForm.roomList[2].split(':')
              if (valueArr[0] && valueArr[1]) {
                roomId = valueArr[0]
                roomName = valueArr[1]
              }
            }
            let builderName = null
            this.builderList.forEach((v) => {
              if (v.id === this.houseForm.builderId) {
                builderName = v.name
              }
            })
            const param = {
              resident: {
                address: this.form.address || null,
                areaNo: this.houseForm.areaNo || null,
                birthday: this.form.birthday || null,
                certNo: this.form.certNo || null,
                certType: this.form.certType || null,
                city: city,
                cityCode: cityCode,
                county: county,
                countyCode: countyCode,
                liveAddress: this.form.liveAddress || null,
                name: this.form.name || null,
                nation: this.form.nation || null,
                nationCode: this.form.nationCode || null,
                phone: this.form.phone || null,
                photo: this.form.photo
                  ? this.form.photo.replace(picBaseUrl, '')
                  : null,
                politicalClimate: this.form.politicalClimate || null,
                province: province,
                provinceCode: provinceCode,
                roomId: roomId,
                sex: this.form.sex || null,
                townNo: this.houseForm.townNo || null,
                education: this.form.education || null,
                hasLivePermit: this.form.hasLivePermit || null,
                isBuyCar: this.form.isBuyCar || null,
                isElecCar: this.form.isElecCar || null,
                isGrid: this.form.isGrid || null,
                isPet: this.form.isPet || null,
                isSoldier: this.form.isSoldier || null,
                isVolunteer: this.form.isVolunteer || null,
                joinPartyDate: this.form.joinPartyDate || null,
                maritalStatus: this.form.maritalStatus || null,
                outDate: this.form.outDate || null,
                outReason: this.form.outReason || null,
                partyRelation: this.form.partyRelation || null,
                workStatus: this.form.workStatus || null,
                workCompany: this.form.workCompany || null,
                ...(this.form.id ? { residentId: this.form.id } : null),
              },
              house: {
                ...this.houseForm,
                unitId: unitId,
                unitName: unitName,
                floorId: floorId,
                floorName: floorName,
                roomId: roomId,
                roomName: roomName,
                builderName: builderName,
              },
              car: {
                ...this.carForm,
                townNo: this.houseForm.townNo || null,
                areaNo: this.houseForm.areaNo || null,
              },
            }
            delete param.house.roomList
            this.isSaving = true
            try {
              let res
              let msgOk = '添加成功！'
              let msgError = '添加失败！'
              if (this.form.id) {
                msgOk = '修改成功！'
                msgError = '修改失败！'
                res = await updateResident(param)
              } else {
                res = await addResident(param)
              }
              if (res && res.status === 0) {
                this.$baseMessage(msgOk, 'success', 'vab-hey-message-success')
                this.$emit('fetch-data')
                this.close()
              } else {
                this.$baseMessage(
                  res ? res.msg : msgError,
                  'error',
                  'vab-hey-message-error'
                )
              }
            } catch (e) {
              this.$baseMessage(
                e ? e.message : '操作失败！',
                'error',
                'vab-hey-message-error'
              )
            }
            this.isSaving = false
          }
        })
      },
      handleAvatarSuccess(res) {
        if (res && res.status === 0 && res.data) {
          // this.imageUrl = URL.createObjectURL(file.raw)
          this.form.photo = picBaseUrl + res.data
          this.$refs.form.validateField('photo')
        } else {
          this.$message.error('图片上传失败，请重试!')
          this.form.photo = ''
          this.$refs.form.validateField('photo')
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG、PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
    },
  }
</script>
<style lang="scss">
  $picWH: 32px;
  $picFont: 14px;
  .resident-modal {
    height: calc(100vh - 250px);
    overflow: auto;
    padding: 0 10px 0 0;
    //width: 666px;
    //margin: 0 auto;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: $picFont;
    color: #8c939d;
    width: $picWH;
    height: $picWH;
    line-height: $picWH;
    text-align: center;
  }
  .avatar {
    width: $picWH;
    height: $picWH;
    display: block;
  }
  .full-select {
    width: 100%;
  }
</style>
